<?php
declare (strict_types = 1);
namespace app\user\logic\teacher;

use app\common\exception\LogicException;
use app\user\model\teacher\Material as MaterialModel;
use app\user\logic\teacher\MaterialCategory as TMC;
use app\common\model\Attach;

class Material extends MaterialModel
{

    /**
     * 讲师数据验证
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-08
     * @return [type] [description]
     */
    public function checkAndReturnTeacher()
    {
        // 讲师权限
        $mid     = static::$mid;
        $teacher = app(Teacher::class)->where('user_id', $mid)->findOrEmpty();
        if ( $teacher->isEmpty() ) throw new LogicException("讲师权限错误");
        return $teacher;
    }

    /**
     * 获取讲师素材列表
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-08
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function getMaterialList($param)
    {
        $teacher = $this->checkAndReturnTeacher();
        // 验证数据
        $this->getValidate()->scene('list')->failException()->check($param);
        // 参数
        $type       = intval($param['type']??1);
        $category   = intval($param['category']??0);
        $title      = $param['title']??'';
        $trashed    = intval($param['trashed']??0);
        $mod        = $trashed ? $this->onlyTrashed() : $this;
        $map        = [];
        $title && $map[] = ['filename', 'LIKE', '%'. $title . '%'];

        if ( 0 !== $category ) $map[] = ['category_id' ,'=', $category];

        $list = $mod->alias('m')
            ->join('attach a', "m.attach_id=a.id")
            ->field('m.id,m.attach_id,m.material_type')
            ->type($type)
            ->teacher($teacher->id)
            ->where($map)
            ->with(['attach_base'])
            ->paginate($this->getListRows())
            ;

        if ( $type == 3 ) {
            foreach ($list as $key => $value) {
                $attach_url         = $value->attach_url;
                $attach_url         = array_column($attach_url, null, 'definition');
                $value->attach_url  = isset($attach_url['OD']) ? $attach_url['OD']['play_url'] : end($attach_url)['play_url'];
            }
        }

        return $list;
    }

    /**
     * 添加素材
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-15
     * @param string $value [description]
     */
    public function addMaterial(array $param)
    {
        $teacher = $this->checkAndReturnTeacher();
        // 验证数据
        $this->getValidate()->scene('add')->failException()->check($param);
        // 参数
        $type       = intval($param['type']??1);
        $cate_id    = intval($param['cate_id']??-1);
        $ids        = explode(',', trim($param['attach_ids']??'', ','));

        if ( !count($ids) ) throw new LogicException("参数错误");
        
        foreach ($ids as $id) {
            $save[] = [
                'teacher_id'    => $teacher->id,
                'material_type' => $type,
                'category_id'   => $cate_id,
                'attach_id'     => $id
            ];
        }

        $re = $this->saveAll($save);
        if ( $re->isEmpty() ) throw new LogicException("添加失败");

        return $re;
    }

    /**
     * 修改素材名称
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-17
     * @return [type] [description]
     */
    public function updateMaterialName(array $param): void
    {
        $teacher = $this->checkAndReturnTeacher();
        // 验证数据
        $this->getValidate()->scene('name')->failException()->check($param);
        // 参数
        $id     = intval($param['id']);
        $title  = $param['title'];
        // 圈子数据
        $data = $this->findOrFail($id);
        if ( $data->teacher_id != $teacher->id ) throw new LogicException("权限错误");
        // 附件
        $attach = Attach::find($data->attach_id);
        $name   = $attach->filename;
        $len    = strlen($name);
        $pos    = stripos($attach->filename, '.');
        // 修改名称
        $attach->filename = $title . substr($name, $pos, $len - $pos);
        if ( !$attach->save() ) throw new LogicException("修改失败");
    }

    /**
     * 修改素材所属分组
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-17
     * @return [type] [description]
     */
    public function updateMaterialCategory(array $param): void
    {
        // 验证数据
        $this->getValidate()->scene('cate')->failException()->check($param);
        // 参数
        $ids    = explode(',', $param['ids']);
        $cate   = intval($param['cate_id']);
        $save   = [];
        foreach ($ids as $id) {
            $save[] = ['id' => intval($id), 'category_id' => $cate];
        }
        $re = $this->saveAll($save);
        if ( $re->isEmpty() ) throw new LogicException("移动失败");

    }

    /**
     * 删除素材
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-17
     * @return [type] [description]
     */
    public function deleteMaterial(array $param): void
    {
        // 验证数据
        $this->getValidate()->scene('delete')->failException()->check($param);
        // 参数
        $ids        = explode(',', $param['ids']);
        $trashed    = !!intval($param['trashed']??0);

        $data = Material::destroy($ids, $trashed);
        if ( !$data ) throw new LogicException("删除失败");

    }

    /**
     * 获取回收站数据
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-17
     * @return [type] [description]
     */
    public function getDeletedMaterial(array $param)
    {
        $teacher = $this->checkAndReturnTeacher();
        // 验证数据
        $this->getValidate()->scene('deleted')->failException()->check($param);
        // 参数
        $type = $param['type'];
        $list = $this
            ->onlyTrashed()
            ->field('id,attach_id,material_type')
            ->type($type)
            ->teacher($teacher->id)
            ->with(['attach_base'])
            ->paginate($this->getListRows())
            ;

        if ( $type == 3 ) {
            foreach ($list as $key => $value) {
                $attach_url         = $value->attach_url;
                $attach_url         = array_column($attach_url, null, 'definition');
                $value->attach_url  = $attach_url['OD']['play_url'];
            }
        }

        return $list;
    }


}
